package kr.co.doriclassic.mypuppystory.searchpuppy;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;

import kr.co.doriclassic.mypuppystory.R;
import kr.co.doriclassic.mypuppystory.alarmpuppy.ChangeFormat;
import kr.co.doriclassic.mypuppystory.alarmpuppy.PreferenceManager;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

//변경할것
public class SearchPuppy extends Activity {
	SidoParser sidoParser;

	ExpandableListView list;

	// 스크롤을 위한 변수
	private LayoutInflater mInflater;
	private PreferenceManager pf;

	private int cyear;
	private int cmonth;
	private int cday;
	private ChangeFormat cf;
	private EditText startdate;
	private EditText enddate;
	private Spinner kindsp;
	private Spinner sidosp;
	private Spinner kugunsp;
	private TextView pageno;

	// 입력값
	private String bgnde; // 유기날짜 검색 시작일(YYYYMMDD)
	private String endde; // 유기날짜 검색 종료일(YYYYMMDD)
	private final static String upkind = "417000"; // 축종코드- 개 : 417000
	private String kind; // 품종코드 api 검색
	private String upr_cd; // 시도코드 - api 검색
	private String org_cd; // 시군구코드 - api 검색
	private String care_reg_no; // 보호소 번호 - api 검색
	private long pageNo; // 페이지번호
	private long totalPageNo;
	private final static int numOfRows = 10; // 한 화면에 보여줄 행수
	private static final String ServiceKey = "ofjOA2C6EaIvtefNoJV5AzhOA2zEaVNKnfVzV8mpPYISSak4Swzd4lXJebG4Url6YY%2FLmZOKxi4JfWrXHJdj6g%3D%3D";
	private String url;

	public SearchPuppy() {
		kind = "";
		upr_cd = "";
		org_cd = "";
		bgnde = "";
		endde = "";
		care_reg_no = "";
		pageNo = 1;
	}

	private void loadUrl() {
		Intent intent = getIntent();
		try {
			String kindcd = intent.getExtras().getString("kindcd");
			if(kind=="")
			kind = kindcd;

		} catch (NullPointerException e) {
		}
		url = "http://openapi.animal.go.kr/openapi/service/rest/abandonmentPublicSrvc/abandonmentPublic?"
				+ "bgnde="
				+ bgnde
				+ "&endde="
				+ endde
				+ "&upkind="
				+ upkind
				+ "&kind="
				+ kind
				+ "&upr_cd="
				+ upr_cd
				+ "&org_cd="
				+ org_cd
				+ "&care_reg_no="
				+ care_reg_no
				+ "&pageNo="
				+ pageNo
				+ "&numOfRows=" + numOfRows + "&ServiceKey=" + ServiceKey;

		new ItemParser(url, SearchPuppy.this, list);
		new ParsingXml().execute(url);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.network_xmlparser);

		pf = new PreferenceManager(SearchPuppy.this);

		kindsp = (Spinner) findViewById(R.id.kindsp);
		sidosp = (Spinner) findViewById(R.id.sidosp);
		kugunsp = (Spinner) findViewById(R.id.kugunsp);
		startdate = (EditText) findViewById(R.id.startdate);
		enddate = (EditText) findViewById(R.id.enddate);

		// 오늘날짜
		Calendar c = Calendar.getInstance();
		cyear = c.get(Calendar.YEAR);
		cmonth = c.get(Calendar.MONTH);
		cday = c.get(Calendar.DAY_OF_MONTH);

		cf = new ChangeFormat();

		startdate.setText(cf.dateToString(cyear, cmonth, cday - 10));
		enddate.setText(cf.dateToString(cyear, cmonth, cday));

		startdate.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				new DatePickerDialog(SearchPuppy.this, new OnDateSetListener() {
					@Override
					public void onDateSet(DatePicker view, int year,
							int monthOfYear, int dayOfMonth) {
						String sCurrent = cf.dateToString(cyear, cmonth, cday);
						String sDate = cf.dateToString(year, monthOfYear,
								dayOfMonth);
						try {
							Log.d("startdate",
									cf.stringToLong(startdate.getText()
											.toString()) + "");
							if (cf.stringToLong(startdate.getText().toString()) > cf
									.stringToLong(enddate.getText().toString())) {
								Toast.makeText(getApplicationContext(),
										"처음 날짜는 마지막 날짜보다 클 수 없습니다.",
										Toast.LENGTH_SHORT).show();
								startdate.setText(sCurrent);
								bgnde = sCurrent.replace("-", "");
							} else {
								startdate.setText(sDate);
								bgnde = sDate.replace("-", "");
							}
						} catch (ParseException e) {
							e.printStackTrace();
						}
					}
				}, cyear, cmonth, cday).show();
			}
		});

		enddate.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				new DatePickerDialog(SearchPuppy.this, new OnDateSetListener() {
					@Override
					public void onDateSet(DatePicker view, int year,
							int monthOfYear, int dayOfMonth) {
						String sCurrent = cf.dateToString(cyear, cmonth, cday);
						String sDate = cf.dateToString(year, monthOfYear,
								dayOfMonth);
						try {
							if (cf.stringToLong(startdate.getText().toString()) > cf
									.stringToLong(enddate.getText().toString())) {
								Toast.makeText(getApplicationContext(),
										"처음 날짜는 마지막 날짜보다 클 수 없습니다.",
										Toast.LENGTH_SHORT).show();
								enddate.setText(sCurrent);
								endde = sCurrent.replace("-", "");
								Log.d("endde", endde);
							} else {
								enddate.setText(sDate);
								endde = sDate.replace("-", "");
								Log.d("endde", endde);
							}
						} catch (ParseException e) {
							e.printStackTrace();
						}
					}
				}, cyear, cmonth, cday).show();
			}
		});

		sidosp.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				upr_cd = (String) pf.loadPref("uprCd" + position, "");
				new KugunParser(
						"http://openapi.animal.go.kr/openapi/service/rest/abandonmentPublicSrvc/sigungu?upr_cd="
								+ upr_cd
								+ "&ServiceKey=ofjOA2C6EaIvtefNoJV5AzhOA2zEaVNKnfVzV8mpPYISSak4Swzd4lXJebG4Url6YY%2FLmZOKxi4JfWrXHJdj6g%3D%3D",
						SearchPuppy.this, kugunsp);
				Log.d("upr_cd", upr_cd + "");
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
			}
		});

		kugunsp.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				org_cd = (String) pf.loadPref("orgCd" + position, "");
				Log.d("org_cd", org_cd + "");
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
			}
		});

		kindsp.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				kind = (String) pf.loadPref("kindCd" + position, "");
				Log.d("kind", kind + "");
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
			}
		});

		list = (ExpandableListView) findViewById(R.id.listView);

		// 파서에 넘겨줌
		loadUrl();

		new SidoParser(
				"http://openapi.animal.go.kr/openapi/service/rest/abandonmentPublicSrvc/sido?ServiceKey=ofjOA2C6EaIvtefNoJV5AzhOA2zEaVNKnfVzV8mpPYISSak4Swzd4lXJebG4Url6YY%2FLmZOKxi4JfWrXHJdj6g%3D%3D",
				SearchPuppy.this, sidosp);
		new KugunParser(
				"http://openapi.animal.go.kr/openapi/service/rest/abandonmentPublicSrvc/sigungu?upr_cd=6110000&ServiceKey=ofjOA2C6EaIvtefNoJV5AzhOA2zEaVNKnfVzV8mpPYISSak4Swzd4lXJebG4Url6YY%2FLmZOKxi4JfWrXHJdj6g%3D%3D",
				SearchPuppy.this, kugunsp);
		new KindParser(
				"http://openapi.animal.go.kr/openapi/service/rest/abandonmentPublicSrvc/kind?up_kind_cd=417000&ServiceKey=ofjOA2C6EaIvtefNoJV5AzhOA2zEaVNKnfVzV8mpPYISSak4Swzd4lXJebG4Url6YY%2FLmZOKxi4JfWrXHJdj6g%3D%3D",
				SearchPuppy.this, kindsp);
		// 푸터를 등록합니다. setAdapter 이전에 해야 합니다.
		mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		list.addFooterView(mInflater.inflate(R.layout.footer, null));

	}

	// 페이지변경
	public void mOnClick(View v) {
		switch (v.getId()) {
		case R.id.searhbutton:
			pageNo = 1;
			loadUrl();
			new ItemParser(url, SearchPuppy.this, list);
			break;

		case R.id.next:
			if (pageNo < totalPageNo) {
				pageNo++;
				loadUrl();
			}
			break;
		case R.id.pre:
			if (pageNo > 1) {
				pageNo--;
				loadUrl();
			}
			break;
		case R.id.first:
			pageNo = 1;
			loadUrl();
			break;
		case R.id.end:
			pageNo = totalPageNo;
			loadUrl();
			break;
		}
	}

	private URL targetURL;
	private XmlPullParser parser;
	private ArrayList<PageInfo> item;
	private PageInfo itemClass;
	private XmlPullParserFactory factory;

	ArrayList<PageInfo> parseItem(String url) {
		targetURL = null;
		parser = null;
		item = new ArrayList<PageInfo>();
		try {
			targetURL = new URL(url);
			InputStream is = targetURL.openStream();
			// Parser
			factory = XmlPullParserFactory.newInstance();
			parser = factory.newPullParser();
			parser.setInput(is, "utf-8");
			boolean init_pageNo = false;
			boolean init_totalCount = false;
			int parserEvent = parser.getEventType();
			while (parserEvent != XmlPullParser.END_DOCUMENT) {
				switch (parserEvent) {
				case XmlPullParser.START_DOCUMENT:
					break;
				case XmlPullParser.START_TAG:
					// item 불러내기
					if (parser.getName().equalsIgnoreCase("totalCount")) {
						itemClass = new PageInfo();
						init_totalCount = true;
					}
					break;
				case XmlPullParser.TEXT:
					if (init_totalCount) {
						itemClass.setTotalCount(parser.getText());
						init_totalCount = false;
					}
					break;
				case XmlPullParser.END_TAG:
					if (parser.getName().equals("totalCount"))
						item.add(itemClass);
					break;
				}
				parserEvent = parser.next();
			}
		} catch (XmlPullParserException | IOException e) {
			e.printStackTrace();
		}
		return item;
	}// parseritem

	public class ParsingXml extends
			AsyncTask<String, Void, ArrayList<PageInfo>> {

		protected void onPreExecute() {
		}

		protected void onPostExecute(ArrayList<PageInfo> result) {
			totalPageNo = (Long.parseLong(result.get(0).getTotalCount()) % 10) > 0 ? (Long
					.parseLong(result.get(0).getTotalCount()) / 10) + 1 : (Long
					.parseLong(result.get(0).getTotalCount()) / 10);
			pageno = (TextView) findViewById(R.id.pageno);
			if (totalPageNo == 0)
				pageno.setText(pageNo + " / " + 1);
			else
				pageno.setText(pageNo + " / " + totalPageNo);
		}

		protected ArrayList<PageInfo> doInBackground(String... params) {
			return parseItem(params[0]);

		}
	}
}